import React from 'react';
import PropTypes from 'prop-types';
import {Spin, Card, Row, Col} from 'antd';
import DataSet from '@antv/data-set';
import {Chart, Geom, Axis, Tooltip, Legend, Label, View} from 'bizcharts';
import styles from './style.css';
import moment from 'moment';
import {injectIntl} from './intl';

export class TablePanel extends React.PureComponent {
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    onClickLegend = (ev, legendItems) => {
        setTimeout(() => {
            const checked = ev.checked;
            const value = ev.item.value;
            if(value === '满足率')
                if(checked) {
                    this.chart.get('views')[0].get('geoms')[0].show();
                } else {
                    this.chart.get('views')[0].get('geoms')[0].hide();
                }
            const newLegend = legendItems.map(d => {
                if(d.value === value)
                    return Object.assign({}, d, {
                        checked,
                    });
                return d;
            });
            this.chart.filter('type', t => {
                const legendCfg = newLegend.find(i => i.value === t);
                return legendCfg && legendCfg.checked;
            });
            
            this.chart.legend({
                items: newLegend
            });
            this.chart.repaint();
        }, 0);
    }
    render() {
        const {
            dataType = [], dataRate = []} = this.props;
        const dataRateBak = dataRate.map(v => ({
            month: v.month,
            BO品种: v.variety,
            BO交付品种: v.deliveryVariety,
            满足率: v.rate
        }));
        //柱状图与折线图
        const dsRate = new DataSet();
        dsRate.setState('type', '');
        const dvRate = dsRate.createView().source(dataRateBak);
        
        dvRate.transform({
            type: 'fold',
            fields: ['BO品种', 'BO交付品种'], // 展开字段集
            key: 'type', // key字段
            value: 'value', // value字段
        })
            .transform({
                type: 'filter',
                callback: d => d.type !== dsRate.state.type
            });
        const scale = {
            满足率: {
                type: 'linear',
                formatter: val => `${val}%`,
                tickCount: 10,
                // ticks: ['0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
                // min: 0,
                // max: 1,
            },
            value: {
                alias: 'BO\n满\n足\n率'
            }
        };
        
        const legendItems = [
            {
                value: 'BO品种',
                marker: {
                    symbol: 'square',
                    fill: '#3182bd',
                    radius: 5
                }
            },
            {
                value: 'BO交付品种',
                marker: {
                    symbol: 'square',
                    fill: '#41a2fc',
                    radius: 5
                }
            },
            {
                value: '满足率',
                marker: {
                    symbol: 'hyphen',
                    stroke: '#fad248',
                    radius: 5,
                    lineWidth: 3
                },
                checked: true
            },
        ];
        //柱状图
        const ds = new DataSet();
        const dv = ds
            .createView()
            .source(dataType)
            .transform({
                type: 'percent',
                field: 'value',
                // 统计销量
                dimension: 'type',
                // 每年的占比
                groupBy: ['month'],
                // 以不同产品类别为分组
                as: 'percent'
            });
        const cols = {
            percent: {
                min: 0,
                formatter(val) {
                    return `${(val * 100).toFixed(2)}%`;
                    // return 'val';
                }
            }
        };
        const label = {
            /**
             * 用于格式化坐标轴上显示的文本信息的回调函数
             * @param  {string} text  文本值
             * @param  {object} item  该文本值对应的原始数据记录
             * @param  {number} index 索引值
             * @return {string}       返回格式化后的文本值
             */
            formatter(text, item, index) {
                // let arr = text.split(' ');
                // return <a>{moment(text).format('Y-MM')}</a>;
                return moment(text).format('Y-MM');
            }
        };
        
        return (
            <div>
                <Spin spinning={this.props.loading}>
                    <Card.Meta
                        title={<Row>
                            <Col>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.column.boRate',
                                    defaultMessage: 'BO满足率'
                                })}
                            </Col>
                        </Row>}
                        description={<Chart height={450} width={500} padding={[50, 50, 100, 50]} forceFit data={dvRate} scale={scale}
                            onGetG2Instance={c => {
                                this.chart = c;
                            }}>
                            <Legend
                                custom
                                allowAllCanceled
                                items={legendItems}
                                onClick={ev => this.onClickLegend(ev, legendItems)} />
                            <Axis name="month" />
                            <Axis name="value" position={'left'} />
                            <Tooltip />
                            <Geom
                                type="interval"
                                position="month*value"
                                color={['type', value => {
                                    if(value === 'BO品种')
                                        return '#2b6cbb';
                                    if(value === 'BO交付品种')
                                        return '#41a2fc';
                                }]}
                                adjust={[{
                                    type: 'dodge',
                                    marginRatio: 1 / 100,
                                }]}>
                                <Label
                                    content="value"
                                    textStyle={{
                                        textAlign: 'center',
                                        fill: '#404040',
                                        fontSize: '12',
                                    }}/>
                            </Geom>
                            <View data={dataRateBak} >
                                <Axis name="满足率" position="right" />
                                <Geom type="line" position="month*满足率" color="#fad248" size={3} >
                                    <Label
                                        content="满足率"
                                        textStyle={{
                                            textAlign: 'start',
                                            fill: '#404040',
                                            fontSize: '12',
                                        }}/>
                                </Geom>
                            </View>
                        </Chart>}/>
                    <div className={styles.divHeight} />
                    <Card.Meta
                        title={<Row>
                            <Col>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.column.boType',
                                    defaultMessage: 'BO分类'
                                })}
                            </Col>
                        </Row>}
                        description={<Chart height={450} data={dv} scale={cols} forceFit>
                            <Legend />
                            <Axis name="month"/>
                            <Axis name="percent" />
                            <Tooltip />
                            <Geom
                                type="intervalStack"
                                // type="interval"
                                position="month*percent"
                                color={'type'}>
                                <Label
                                    content="value"
                                    textStyle={{
                                        textAlign: 'center', // 文本对齐方向，可取值为： start middle end
                                        fill: '#ffffff', // 文本的颜色
                                        fontSize: '12', // 文本大小
                                        // fontWeight: 'bold', // 文本粗细
                                        // textBaseline: 'middle' // 文本基准线，可取 top middle bottom，默认为middle
                                    }}
                                    offset={-1}
                                    position="middle" />
                            </Geom>
                        </Chart>}/>
                    <div className={styles.divHeight} />
                </Spin>
            </div>
        );
    }
}

TablePanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    dataRate: PropTypes.array.isRequired,
    dataType: PropTypes.array.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    hasError: PropTypes.string,
    intl: PropTypes.object,
    loading: PropTypes.bool,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
import {saveQueryCondition} from './actions';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'data']),
    init => {
        const initData = init.toJS();
        const dealers = initData ? initData.map(item => ({
            text: `${'('}${item.code}${')'}${item.country}`,
            value: item.id
        })) : [];
        return {
            dealers
        };
    }
);
const getTypeData = selectorFactory(['page', 'domainData', 'listType', 'data']);
const getDataRate = selectorFactory(['page', 'domainData', 'listRate', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const mapStateToProps = state => ({
    dataType: getTypeData(state),
    dataRate: getDataRate(state),
    loading: state.getIn(['page', 'domainData', 'listType', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'listType', 'hasError']),
    initEnum: getInitData(state),
    conditions: getConditions(state),
});
const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
